--[[
	百家乐机器人
]]

local skynet = require("skynet")
local Timer = require("Timer")
local math_random = math.random
local table_copy = table.copy
local table_remove = table.remove
local string_split = string.split
local table_insert = table.insert
local math_floor = math.floor

local Robot = class("Robot")

function Robot:ctor(robot_manager)

	self.close = true
	self.robot_manager = robot_manager
	self.can_bet_chip = 0 --当前局可下注额度			
	self.bet_list = {} --下注时间内
	self.bet_id = 1 --这局主要下的位置
	self.can_bet = true --这局是否可以下注
end

--注册消息
function Robot:register()

	self.robot_manager:registerMessage(self.uid, "table.NTF_PLAYER_ENTER", handler(self, self.playerEnterNtf))
	self.robot_manager:registerMessage(self.uid, "table.NTF_LEAVE", handler(self, self.leaveNtf))
	self.robot_manager:registerMessage(self.uid, "table.NTF_SITDOWN", handler(self, self.sitdownNtf))
	self.robot_manager:registerMessage(self.uid, "table.NTF_STANDUP", handler(self, self.standUpNtf))
	self.robot_manager:registerMessage(self.uid, "table.NTF_MONEY_CHANGED", handler(self, self.moneyChangeNtf))	

	self.robot_manager:registerMessage(self.uid, "table.RSP_STANDUP", handler(self, self.standUpRsp))
	self.robot_manager:registerMessage(self.uid, "table.RSP_PLAYER_LIST", handler(self, self.playerListRsp))
	self.robot_manager:registerMessage(self.uid, "table.RSP_SITDOWN", handler(self, self.sitdownRsp))	
	self.robot_manager:registerMessage(self.uid, "table.RSP_LEAVE", handler(self, self.leaveRsp))
	self.robot_manager:registerMessage(self.uid, "table.RSP_CHAT", handler(self, self.chatRsp))	
	self.robot_manager:registerMessage(self.uid, "table.RSQ_USE_MAGIC_PICTURE", handler(self, self.magicRsp))

	self.robot_manager:registerMessage(self.uid, "hall.NTF_USER_MONEY", handler(self, self.userMoneyNtf))

	self.robot_manager:registerMessage(self.uid, "baijiale.NTF_START", handler(self, self.startNtf))
	self.robot_manager:registerMessage(self.uid, "baijiale.NTF_GAMEOVER", handler(self, self.gameoverNtf))
	self.robot_manager:registerMessage(self.uid, "baijiale.NTF_REST", handler(self, self.restNtf))
	self.robot_manager:registerMessage(self.uid, "baijiale.NTF_BET", handler(self, self.betNtf))
	self.robot_manager:registerMessage(self.uid, "baijiale.NTF_START_BET", handler(self, self.startBetNtf))
	self.robot_manager:registerMessage(self.uid, "baijiale.NTF_STOP_BET", handler(self, self.stopBetNtf))

	self.robot_manager:registerMessage(self.uid, "baijiale.RSP_BET", handler(self, self.betRsp))
	self.robot_manager:registerMessage(self.uid, "baijiale.RSP_RATE_TYPE", handler(self, self.rateTypeRsp))
		
end

function Robot:init(uid)
	self.close = false
	self.uid = uid	
	self.user_manager = global.user_manager
	self.room_config = global.room_config
	self.rule = global.rule
	self.desk = global.desk
	self.bairen_desk = global.bairen_desk
	self.user = self.user_manager:getUser(uid)

	self.server_id = self.room_config:getServerId()
 	self.table_id = self.room_config:getTableId()
 	self.table_type = self.room_config:getTableType()
 	self.table_gid = self.room_config:getTableGid()
 	self.game_type = self.room_config:getGameType()
 	self.table_pattern = self.room_config:getTablePattern()	
 	self.room_data = self.room_config:getRoomData()		

 	self.robot_type = self.user:getRobotTypeId() --机器人类型id 1:非R型机器人 2：小R型机器人 3:中R型机器人 4：大R型机器人 5：土豪型机器人
 	self.config = self.room_config:getRobotConfig(self.robot_type) --robot.lua配置
    self.life_duration  = math_random(5 * 60, 30 * 60) --机器人生命周期 10分钟~60分钟
    self.start_time = os.time() --开始时间
	self.can_sitdown = false --不可坐下
	self.req_sit_time = 0 --请坐下的时间

    --可下注列表
	local can_bet_list = self.desk:getCanBetList("bjl_bet_list", self.user:getCoins())
	self.user:setCanBetList(can_bet_list)


 	self:register()
 	self:enterRsp()
 	self:canBet()

end

function Robot:clear()
	if self.close then 
		return 
	end				
	self.close = true
	local seat_id = self.user:getSeatId()
	self.robot_manager:removeRobot(self.uid)	
	self.user = nil
	self.uid = nil	
	self.can_sitdown = false --不可坐下
	self.req_sit_time = 0 --请坐下的时间

    -- if seat_id == 1 or seat_id == 4 then 
    -- 	self.bairen_desk:specialRobotSitdown()
    -- end		

end

--是否处于关闭中
function Robot:isClose()
	-- dbglog("__加载机器人数量____1111_______1_",self.close)
	return self.close
end

function Robot:getUser()
	return self.user
end

--发消息给桌子
function Robot:send(message_name, data)
	local fd = -1
	self.robot_manager:dispatch(message_name, self.uid, fd, data)
end

--一个定时驱动逻辑
function Robot:update()	
	if self.close then 
		return 
	end
	if self.can_sitdown and self.req_sit_time < os.time() then 
		self:sitdownReq()
		self.req_sit_time = 0 
		self.can_sitdown = false
	end	
	if self.desk:getState() == "bet" then 
		--下注
		self:betReq()
	end
end

function Robot:isBanker()
	return false
end

function Robot:checkSitdown()
	if self.can_sitdown then 
		return 
	end
	if self.user:isSeated() then 
		return 
	end
	--robot.lua配置
	local vip_seat_rate = tonumber(self.config.vip_seat_rate)
	local rand = math_random(1, 100) 		
	if rand > vip_seat_rate  then --坐下的概率
		return 
	end
	self.can_sitdown = true
	self.req_sit_time = os.time() + math_random(1,20)
end

-------------
-----------------------------------------------------
--nt
-----------------------------------------------------
function Robot:playerEnterNtf()	
end
function Robot:leaveNtf(data)	
	if data.uid ~= self.uid then 
		return 
	end
	self:clear()
end


function Robot:sitdownNtf(data)	
end
function Robot:standUpNtf(data)	
	if data.uid ~= self.uid then 
		return
	end
	local seat_id = data.seat_id
    -- if seat_id and seat_id == 1 or seat_id == 4 then 
    -- 	self.bairen_desk:specialRobotSitdown()
    --     dbglog("_robot_standUpNtf________", self.uid, seat_id)
    -- end	
end
function Robot:moneyChangeNtf(data)	
end

--开始
function Robot:startNtf()

	self:getCanBetCoins()

	if self.user_manager:getSeatUserNum() < 6 then 
		self:checkSitdown()
	end	
end

--结束
function Robot:gameoverNtf(data)

end

--休息
function Robot:restNtf(data)

	self.config = self.room_config:getRobotConfig(self.robot_type)
	local seat_id = self.user:getSeatId() 		
	self:leaveDesk()	
	self:canBet()
end

function Robot:betNtf()
	-- errlog("robot_111___ntfBet___")
end
function Robot:startBetNtf()
	-- errlog("robot_222___ntfBet___")
end

function Robot:stopBetNtf()
	
end
--进入桌子
-- function Robot:enterReq()	
-- end
function Robot:enterRsp()		
	
end

--坐下
function Robot:sitdownReq(seat_id)	
	if self.close then 
		return 
	end
	local user = self.user
	if not user then
		return 
	end 
	if seat_id then 
		self:send("REQ_SITDOWN", {seat_id=seat_id}) 
		return 
	end
	if self.user_manager:getSeatUserNum() >= 6 then
		return
	end	
    --金币是否够可以坐下
    local sitdown_coin = self.room_config:getSitdownCoin()
    if user:getCoins() < sitdown_coin then --小于最小可坐下需要的金币
        return
    end	
	if user:isSeated() then --已坐下
		return 
	end
	if self.can_sitdown then 
		self:send("REQ_SITDOWN", {seat_id=seat_id}) 
		return 
	end
end

function Robot:sitdownRsp(data)	
	if data.result and data.result > 0 then 
		dbglog("_____坐下回复错误____sitdownRsp_______",self.uid, self.user:getName(),  data)
	end
	self.can_sitdown = false
end

function Robot:standUpReq()	
	local user = self.user_manager:getUser(self.uid)
	if not user then 
		return 
	end
 	self:send("REQ_STANDUP", {seat_id=user:getSeatId()})
end
function Robot:standUpRsp(data)
	-- print("_________standUpRsp_______",  data)
end

--下注
function Robot:betReq()		
	if not self:getCanBet() then 
		return 
	end

	local user = self.user_manager:getUser(self.uid)
	if not user then return end 
	local bet_chip = table_remove(self.bet_list)
	local user_chip = user:getCoins()
	if not bet_chip or bet_chip <= 0 then 
		return 
	end
	if user_chip < bet_chip then 
		return
	end		
    local data = {
		bet_chip = bet_chip,
		pool_id = self:getBetPoolId(),
		bet_type = 0,
    }
    -- errlog("___3333________REQ_BET______",self.uid, self.room_config:getRoomName())
	self:send("REQ_BET", data)
end
function Robot:betRsp(data)	
	-- dbglog("___22222_________betRsp_______",  data)
	
end

--免佣模式
function Robot:rateTypeReq(rate_type)	
	local data = {rate_type = 1}
	self:send("REQ_RATE_TYPE", data)
end
function Robot:rateTypeRsp(data)
	-- print("____Robot:rateTypeRsp__________________",  data)
end

function Robot:playerListRsp()	
end

function Robot:leaveReq()		
	-- print("_______Robot leaveReq____")	
    self:send("REQ_LEAVE")
end
function Robot:leaveRsp(data)	
	if not data then 		
		return 
	end	
	if data.result == 0 then 			
		--可以离开		
		self:clear()		
	end
end

function Robot:chatReq()	
	local data = {
		type = 2, --1表示表情 2文本 3语音
		picture_id = 2, --id
		content = "你好", --文本内容
		voice = nil, --语音内容
		content_id = nil, --文本i
	}
	self:send("REQ_CHAT", data)	
end
function Robot:chatRsp(data)	
	-- print("____Robot:chatRsq__________________",  data)

end

--发送魔法表情
function Robot:magicReq()	
	local users = self.user_manager:getSeatUsers()
	local user = users[math_random(1, #users)]
	local uid = user:getUid()
	if uid == self.uid then 
		return 
	end
	local data = {
		dst_id = uid,
		picture_id = math_random(1, 3),
	}
	self:send("REQ_USE_MAGIC_PICTURE", data)
	-- dbglog("___22222_________magicReq_______",  data)	
end
function Robot:magicRsq(data)		
	-- dbglog("___22222_________magicRsq_______",  data)	
end


----------------------------------------------------------------
-- hall
----------------------------------------------------------------
function Robot:userMoneyNtf(data)		

end


----------------------------------------------------------------

----------------------------------------------------------------
--是否可下注
function Robot:getCanBet() 
	return self.can_bet
end

--机器人这局是否可以下注
function Robot:canBet() 
	local rate = self.config.bet_rate or 100
	local num = math_random(1,100)
	self.can_bet = true
	if num > rate then 
		self.can_bet = false
	end
	return self.can_bet
end

-- [1] = {
--  ["count_range"] = "5,15", --人数
--  ["coins_range"] = "500,20000", --携带
--  ["leave_rate"] = 20, --离桌率
--  ["system_bet_min"] = 20000, --下注下限
--  ["system_last_bet_rate"] = 30, --上局选用比例
--  ["system_bet_area"] = "1,5", --下注特殊位置的概率
--  ["bet_area_float"] = "85-180", --下注浮动
--  ["vip_seat_rate"] = 50, --上位率
-- },
--取要下注的位置
function Robot:getBetPoolId()	
	local config = self.config --robot.lua配置
	local area_rate = string_split(config.system_bet_area, ",")
	if not area_rate[1] or not area_rate[2] or tonumber(area_rate[1])>tonumber(area_rate[2]) then 
		return 1
	end
	local num = math_random(1, 100)
	if tonumber(area_rate[1]) < num and num < tonumber(area_rate[2]) then
		local tb = {2,4,5}
		return tb[math_random(1,#tb)]
	end	
	local num = math_random(1,100)
	local bet_pools = {}
	if num < 60 then 	
		return 1 --闲
	else
		return 3 --庄
	end
end

--机器人可下注额度
-- = 小R / 小R可下总额 * 小R所剩余的金币总和
function Robot:getCanBetCoins() 
	self.bet_list = {}
	if not self:getCanBet() then 
		return 
	end
	local user = self.user
	local coins = user:getCoins()
	if coins <= 0 then 
		return 
	end	
    local robot_type_id = user:getRobotTypeId()
    local side_bet_coins = self.robot_manager:getCanBetCoins(robot_type_id)    
    local robot_total_coins = self.robot_manager:getTotalCoins(robot_type_id)
    local can_bet_chip = 0 
    if robot_total_coins > 0 and side_bet_coins > 0 then 
    	can_bet_chip = math_floor( (coins or 0) / robot_total_coins * side_bet_coins ) --能下注的金币 
    end 
	local can_bet_list = user:getCanBetList() --可下注列表
	dbglog("___2__bjl________getCanBetCoins___", can_bet_list)	

    local index = #can_bet_list
    while true do
        local k = index
        if k < 1 then
            break
        end
        local tmp_bet_coins = can_bet_list[k]
        if (coins >= tmp_bet_coins) and (can_bet_chip >= tmp_bet_coins) then
            table_insert(self.bet_list, tmp_bet_coins)
            coins = coins - tmp_bet_coins
            can_bet_chip = can_bet_chip - tmp_bet_coins
        else
            index = index - 1
        end
    end
    dbglog("___3__bjl________getCanBetCoins___", index, #self.bet_list)	

	for k = #self.bet_list, 30 do 
	    table_insert(self.bet_list, 0)
	end
	table.mix(self.bet_list) 
    
end

--离桌
function Robot:leaveDesk()	
	if self.close then 
		return 
	end	
	if not self.user then 
		return 
	end
	-- local seat_id = self.user:getSeatId() 
	-- if seat_id == 1 then 
	-- 	self:leaveReq()	
	-- 	return 
	-- end
    --金币是否够可以坐下
    local sitdown_coin = self.room_config:getSitdownCoin()
    if self.user:isSeated() and self.user:getCoins() < sitdown_coin then --小于最小可坐下需要的金币
    	self:leaveReq()
        return
    end		
	--金币不足时离桌
	local bet_list = self.user:getCanBetList()	
	if self.user:getCoins() < bet_list[1]then 		
		self:leaveReq()	
		dbglog("机器人金币不足时离桌________",self.uid)
		return 
	end	
	
    --机器人有一定概率的离桌率	
    local leave_rate = self.config.leave_rate or 5
    if math_random(1,100) <= leave_rate then    	
        self:leaveReq()        
        dbglog("机器人有一定概率的离桌率", leave_rate)
        return
    end 	
    --一定时间内要离桌
    local curr_time = os.time()
    if curr_time - self.start_time > self.life_duration then
    	dbglog("机器人一定时间内要离桌",self.uid, self.life_duration)
        self:leaveReq()        
        self.start_time = curr_time --机器人生命周期 10分钟~60分钟       
        return
    end
end








return Robot